package controller

import (
	"bytes"
	"errors"
	"fmt"
	"gitee.com/chejiangyi/bsfgo/core/base2"
	"gitee.com/chejiangyi/bsfgo/core/utils"
	"gitee.com/chejiangyi/bsfgo/gin2/template2"
	"gitee.com/chejiangyi/bsfgo/gin2/utils2"
	"github.com/gin-gonic/gin"
	"net/http"
)

type BaseWebController struct {
	BaseApiController // 继承 BaseApiController
}

// Html 优先调用接口方法，否则使用默认实现
func (m *BaseWebController) Html(c *gin.Context, template string, data gin.H) {
	data["T"] = template2.BaseTemplateTool{}
	data["C"] = c
	data["content_template"] = template
	m.ReaderTemplate(c, template, data)
}

// ReaderTemplate 优先调用接口方法，否则使用默认实现
func (m *BaseWebController) ReaderTemplate(c *gin.Context, template string, data gin.H) {
	if base2.BsfConfigInstance.GetTemplatePageCacheRenderEnabled() {
		var buf2 []byte
		utils.BufPoolUtil.GetBufToFuc(func(buf *bytes.Buffer) {
			m.RenderFromWithTemplateCache(buf, template, []string{base2.BsfConfigInstance.GetTemplatePath() + template}, data)
			buf2 = buf.Bytes()
		})
		_, err := c.Writer.Write(buf2)
		if err != nil {
			panic(base2.NewBsfError2("模版输出出错", err))
		}
	} else if base2.BsfConfigInstance.GetTemplateLoadHTMLGlobEnabled() {
		c.HTML(http.StatusOK, template, data)
	}
}

// CatchHtmlError 优先调用接口方法，否则使用默认实现
func (m *BaseWebController) CatchHtmlError(c *gin.Context) {
	if err := recover(); err != nil {
		utils.LogUtil.Error2("【页面访问异常】%v\r\n【参数信息】%v\r\n【错误详情】%v",
			c.Request.URL.Path, utils2.WebUtil.GetRequestInfo(c), err)
		var bsfError *base2.BsfBizError
		ok := errors.As(utils.ErrorUtil.ConvertToError(err), &bsfError)
		errorMsg := ""
		if base2.BsfConfigInstance.GetWebResponseDetailErrorEnabled() {
			if ok {
				errorMsg = bsfError.ToJson()
			} else {
				errorMsg = fmt.Sprintf("详细信息:%v", err)
			}

		} else {
			if ok {
				errorMsg = bsfError.ToJsonNoTrace()
			} else {
				errorMsg = "详细信息请联系网站运维人员"
			}
		}
		m.ReaderTemplate(c, base2.BsfConfigInstance.GetTemplateErrorTemplate(), gin.H{"error": errorMsg})
		//c.Set("error", errorMsg)
		//c.Redirect(http.StatusFound, base2.BsfConfigInstance.GetTemplateErrorUrlPath())
	}
}

// RenderFromWithTemplateCache 从缓存渲染模板（优先调用接口方法）
func (m *BaseWebController) RenderFromWithTemplateCache(buf *bytes.Buffer, tmplName string, filenames []string, data interface{}) {
	tmpl := template2.TemplateUtil.TryGetTemplateFromCache(tmplName, filenames)
	template2.TemplateUtil.RenderTemplate(buf, tmplName, tmpl, data)
}
